<template>
  <view class="container">
    <!-- 搜索框（始终显示） -->
    <view class="header">
      <view class="searchbox">
        <view class="inp">
          <input v-model="searchValue" type="text" placeholder="猜你想搜索" />
        </view>
        <view class="btn" @click="handleSearch">
          <text class="search-text">搜索</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="searchLoading" class="loading-mask">
      <view class="loading-content">
        <up-icon type="loading" size="40"></up-icon>
        <text>搜索中...</text>
      </view>
    </view>

    <!-- 搜索结果区域（搜索后显示） -->
    <view v-else-if="isSearching" class="search-result">
      <!-- 结果统计 -->
      <view class="result-count">
        <text>找到 {{ searchResult.length }} 条相关内容</text>
      </view>

      <!-- 结果列表 -->
      <view class="result-list" v-if="searchResult.length > 0">
        <view class="post-card" v-for="(article, index) in searchResult" :key="article.id" @click="goToArticle(article.id)">
          <view class="post-header">
            <!-- 点击头像跳转到用户详情页面 -->
            <up-avatar :src="article.user.avatar" size="40" @click="navigateToProfile(article.userId)"></up-avatar>
            <view class="user-info">
              <text class="username">{{ article.user.nickname || '匿名用户' }}</text>
            </view>
            <text class="post-time">{{ formatDate(article.createTime) }}</text>
          </view>

          <view class="post-content">
            <text class="article-title">{{ article.title }}</text>
            <text class="article-content">{{ article.content }}</text>
            <view v-if="article.flie" class="image-container">
              <view class="multi-images">
                <up-image
                    v-for="(imgUrl, idx) in parseImageUrls(article.flie)"
                    :key="idx"
                    :src="imgUrl"
                    mode="aspectFill"
                    width="220rpx"
                    height="220rpx"
                    class="image-item"
                    @error="handleImageError"
                ></up-image>
              </view>
            </view>
          </view>

          <view class="post-footer">
            <view class="action-item">
              <up-icon name="eye" size="22" color="#909399"></up-icon>
              <text>{{ formatViewCount(article.viewCount) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 无结果提示 -->
      <view class="no-result" v-else>
        <up-icon type="search" size="80" color="#ccc"></up-icon>
        <text>未找到相关内容</text>
        <button class="clear-btn" @click="resetSearch">重新搜索</button>
      </view>
    </view>

    <!-- 搜索前显示的内容（历史搜索和热搜排行） -->
    <view v-else>
      <!-- 历史搜索 -->
      <view class="history" v-if="historyList.length > 0">
        <view class="title clearfix">
          <text>历史搜索</text>
          <text class="clear" @click="showClearHistoryModal">
            <up-icon type="trash" size="20"></up-icon>
            清空历史
          </text>
        </view>
        <view class="history-wrapper">
          <view class="history-list">
            <up-tag
                v-for="(item, index) in historyList"
                :key="index"
                :text="item"
                mode="plain"
                shape="circle"
                @click="reSearch(item)"
                style="margin-right: 20rpx; margin-bottom: 20rpx;"
            ></up-tag>
          </view>
        </view>
      </view>

      <!-- 热搜排行 -->
      <view class="searchTop">
        <view class="tabs">
          <text :class="{ active: activeTab === 'school' }" @click="activeTab = 'school'">
            <up-icon type="fire" size="20" color="#ff5722"></up-icon>
            同校热榜
          </text>
        </view>
        <view class="hotList">
          <view v-for="(item, index) in hotList.slice(0, 10)" :key="index" class="hotItem" @click="goToArticle(item.id)">
            <text class="rank">{{ index + 1 }}</text>
            <text class="title">{{ item.title }}</text>
            <text class="viewCount">{{ formatViewCount(item.viewCount) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { searchArticlesByTitle, getAllArticles } from '@/apis/homeAPI';

// 搜索相关状态
const searchValue = ref('');
const historyList = ref([]);
const isSearching = ref(false);
const searchResult = ref([]);
const searchLoading = ref(false);
const searchError = ref('');

// 热搜相关状态
const activeTab = ref('school');
const hotData = reactive({
  school: [],
});

const hotList = computed(() => hotData[activeTab.value]);
// 解析图片URL
const parseImageUrls = (flieStr) => {
  try {
    if (!flieStr) return [];
    const urls = JSON.parse(flieStr);
    return Array.isArray(urls) ? urls.filter(url => typeof url === 'string' && url.trim() !== '') : [];
  } catch (error) {
    console.error('图片解析失败:', error, '原始数据:', flieStr);
    return [];
  }
};

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.detail);
  event.target.src = '/static/default-image.png'; // 替换为你的默认图片路径
};
// 搜索逻辑
async function handleSearch() {
  const title = searchValue.value.trim();
  if (!title) return;

  searchLoading.value = true;
  searchError.value = '';

  try {
    const response = await searchArticlesByTitle(title);
console.log(response);
    // 处理响应数据，注意这里要根据实际返回的响应结构来取数据
    if (response.data && response.data.code === 200) {
      searchResult.value = response.data.data || [];
      isSearching.value = true;

      // 更新历史记录
      if (!historyList.value.includes(title)) {
        historyList.value.unshift(title);
        saveHistory();
      }
    } else {
      searchError.value = response.data.msg || '搜索失败';
      uni.showToast({ title: searchError.value, icon: 'none' });
    }
  } catch (error) {
    console.error('搜索出错:', error);
    searchError.value = '网络错误，请重试';
    uni.showToast({ title: searchError.value, icon: 'none' });
  } finally {
    searchLoading.value = false;
  }
}

// 重新搜索历史记录
function reSearch(item) {
  searchValue.value = item;
  handleSearch();
}

// 重置搜索状态（仅重置搜索结果，不涉及返回功能）
function resetSearch() {
  isSearching.value = false;
  searchValue.value = '';
  searchResult.value = [];
  searchError.value = '';
}

// 历史记录相关方法
function showClearHistoryModal() {
  uni.showModal({
    title: '提示',
    content: '是否清空历史记录？',
    success: (res) => {
      if (res.confirm) {
        clearHistory();
      }
    }
  });
}

function clearHistory() {
  historyList.value = [];
  saveHistory();
}

function saveHistory() {
  uni.setStorageSync('searchHistory', historyList.value);
}

function loadHistory() {
  const storedHistory = uni.getStorageSync('searchHistory');
  if (storedHistory) {
    historyList.value = storedHistory;
  }
}

// 工具函数
function formatDate(dateString) {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function formatViewCount(count) {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + 'w';
  } else if (count >= 1000) {
    return (count / 1000).toFixed(1) + 'k';
  }
  return count.toString();
}

const goToArticle = (id) => {
  uni.navigateTo({
    url: `/pages/article/article?id=${id}`
  });
};

// 跳转到 profile 页面的函数
const navigateToProfile = (userId) => {
  uni.navigateTo({
    url: `/pages/profile/profile?userId=${userId}`
  });
};

// 获取所有帖子
async function fetchAllArticles() {
  try {
    const response = await getAllArticles();
    console.log('获取帖子成功:', response);

    if (response.data && response.data.code === 200) {
      // 将所有帖子数据赋值给同校热榜数据
      hotData.school = response.data.data || [];
    } else {
      uni.showToast({ title: response.data.msg || '获取帖子失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取帖子出错:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
}

onMounted(() => {
  loadHistory();
  fetchAllArticles();
});
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.header {
  width: 100%;
  padding: 10rpx 0;
  position: sticky;
  top: 0;
  background-color: #f9f9f9;
  z-index: 10;

  .searchbox {
    display: flex;
    align-items: center;

    .inp {
      flex: 1;
      height: 70rpx;
      background-color: #f5f5f5;
      border-radius: 35rpx;
      padding: 0 30rpx;
      display: flex;
      align-items: center;
      font-size: 28rpx;
    }

    .btn {
      width: 120rpx;
      height: 70rpx;
      margin-left: 20rpx;
      background-color: #007aff;
      border-radius: 35rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .search-text {
        color: white;
        font-size: 30rpx;
        font-weight: 500;
      }
    }
  }
}

/* 加载遮罩 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;

  .loading-content {
    background-color: white;
    padding: 40rpx;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}

/* 搜索结果样式 */
.search-result {
  margin-top: 20rpx;

  .result-count {
    padding: 15rpx 0;
    font-size: 26rpx;
    color: #666;
    border-bottom: 1px solid #eee;
  }

  .result-list {
    margin-top: 20rpx;
  }

  .post-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 25rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;
  }

  .post-card:active {
    transform: scale(0.99);
  }

  .post-header {
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    margin-bottom: 25rpx;
    position: relative;
  }

  .user-info {
    margin-left: 20rpx;
  }

  .username {
    font-size: 32rpx;
    font-weight: 500;
    color: #1c0101;
    display: block;
  }

  .post-time {
    position: absolute;
    right: 0;
    top: 0;
    font-size: 24rpx;
    color: #999;
  }

  .post-content {
    font-size: 30rpx;
    color: #333;
    line-height: 1.6;
    margin-bottom: 25rpx;
  }

  .article-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
  }

  .article-content {
    display: block;
    margin-top: 15rpx;
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .image-item {
    margin-top: 15rpx;
  }

  .article-image {
    width: 100%;
    height: auto;
    border-radius: 8rpx;
  }

  .post-footer {
    display: flex;
    padding-top: 20rpx;
    border-top: 1rpx solid #ebeef5;
  }

  .action-item {
    display: flex;
    align-items: center;
    margin-right: 40rpx;
    color: #909399;
    font-size: 26rpx;
  }

  .action-item text {
    margin-left: 8rpx;
  }

  .no-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 150rpx 0;

    text {
      margin-top: 30rpx;
      font-size: 28rpx;
      color: #999;
    }

    .clear-btn {
      margin-top: 40rpx;
      width: 200rpx;
      height: 60rpx;
      line-height: 60rpx;
      background-color: #007aff;
      color: white;
      font-size: 28rpx;
      border-radius: 30rpx;
    }
  }
}

/* 搜索前显示的内容样式（历史搜索和热搜） */
.history {
  padding: 20rpx 0;

  .title {
    font-size: 30rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .clear {
      font-size: 28rpx;
      color: #ff5722;
      display: flex;
      align-items: center;

      up-icon {
        margin-right: 10rpx;
      }
    }
  }

  .history-wrapper {
    background-color: #ffffff;
    border-radius: 10rpx;
    padding: 20rpx;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    up-tag {
      font-size: 28rpx;
      color: #333;
      background-color: #f5f5f5;
      padding: 10rpx 20rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
    }
  }
}

.searchTop {
  padding: 20rpx 0;

  .tabs {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20rpx;

    text {
      font-size: 30rpx;
      color: #666;
      margin-right: 30rpx;
      display: flex;
      align-items: center;

      &.active {
        color: #ff5722;
        font-weight: bold;

        up-icon {
          color: #ff5722;
        }
      }

      up-icon {
        margin-right: 10rpx;
      }
    }
  }

  .hotList {
    background-color: #fffaf0;
    border-radius: 10rpx;
    padding: 20rpx;

    .hotItem {
      display: flex;
      align-items: center;
      padding: 15rpx 0;
      border-bottom: 1px solid #fff0e0;

      &:last-child {
        border-bottom: none;
      }

      .rank {
        font-size: 28rpx;
        color: #ff5722;
        margin-right: 20rpx;
        font-weight: bold;
        width: 40rpx;
        text-align: center;
      }

      .title {
        font-size: 28rpx;
        color: #333;
        flex: 1;
        line-height: 1.4;
      }

      .viewCount {
        font-size: 24rpx;
        color: #ff5722;
        white-space: nowrap;
      }
    }
  }
}
.image-container {
  margin-top: 15rpx;
}
.multi-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}
.image-item {
  margin-bottom: 10rpx;
  border-radius: 8rpx;
  overflow: hidden;
}
</style>